package com.twu.biblioteca.command;

import com.twu.biblioteca.Book;
import com.twu.biblioteca.Library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 * User: twer
 * Date: 5/30/13
 * Time: 8:25 AM
 * To change this template use File | Settings | File Templates.
 */
public class ReserveBookCommand implements Command {
    private InputStreamReader inputStreamReader;
    private PrintWriter printWriter;
    private Library library;

    public ReserveBookCommand(InputStreamReader inputStreamReader, PrintWriter printWriter, Library library) {
        this.inputStreamReader = inputStreamReader;
        this.printWriter = printWriter;
        this.library = library;
    }

    @Override
    public String execute() {
//        result.append(showBookList());
        printWriter.println(showBookList());
        printWriter.print("Input Id to reserve book:");
        printWriter.flush();
        StringBuilder result = new StringBuilder();
        result.append(reserveBook());
        return result.toString();
    }

    private String reserveBook() {
        StringBuilder sb = new StringBuilder();
        String option = readUserInput();

        int id;
        try {
            id = Integer.valueOf(option);
        } catch (NumberFormatException e) {
            sb.append("\nSelect a valid option!!\n");
            return sb.toString();
        }
        if (id < 1 || id > library.getBooks().size()) {
            sb.append("\nSelect a valid option!!\n");
            return sb.toString();
        }

        if(library.reserveById(id - 1)){
            sb.append("Thank You! Enjoy the book.").append("\n");
        }else {
            sb.append("Sorry we don't have that book yet.").append("\n");
        }

        return sb.toString();
    }

    private String showBookList() {
        StringBuilder sb = new StringBuilder();
        int i = 1;
        for (Book book : library.getBooks()) {
            sb.append("\t").append(i++).append(" ").append(book.getName()).append("\n");
        }
        return sb.toString();
    }

    private String readUserInput() {
        BufferedReader br = new BufferedReader(inputStreamReader);

        String userInput = "";
        try {
            userInput = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (userInput == null)
            return "";

        return userInput;
    }
}
